package tech.deepmind.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import tech.deepmind.entity.Role;
import tech.deepmind.entity.User;
import tech.deepmind.service.RoleService;
import tech.deepmind.service.UserService;
import tech.deepmind.util.Constants;
import tech.deepmind.util.PageSupport;

/**
 * @Desc
 * @Author DeepMind
 * @Date 2021年5月19日 下午2:28:12
 * @Version 1.01
 */
@Controller
@RequestMapping("/user")
public class UserHandler {

	private Logger logger = LogManager.getLogger();
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;

	@RequestMapping(value = "index")
	public String index() {
		return "login";
	}
	
	@RequestMapping(value = "login")
	public String login(String userName,String password,Model model,HttpSession session) {
		User user = userService.login(userName, password);
		System.out.println(user);
		//System.out.println(1/0);
		if (user!= null) {
			session.setAttribute("user", user);
//			request.setAttribute("msg", "请求信息");
			//return "frame";
//			return "forward:frame";//请求转发
			return "redirect:frame";//重定向
		}
		model.addAttribute("msg", "账号或密码有误！");
		return "login";
	}
	
	
	
	/*
	 局部异常
	@ExceptionHandler(value = java.lang.RuntimeException.class)
	public String handlerExceptionResolver(RuntimeException e,HttpServletRequest request) {
		request.setAttribute("e", e);
		return "error";
	}
	*/
	
	@RequestMapping(value = "frame")
	public String main(HttpSession session) {
		User user =  (User) session.getAttribute("user");
		if (user == null) {
			session.setAttribute("msg", "没有登录，请登录");
			return "redirect:index";
		}		
		return "frame";
	}
	
	@RequestMapping(value="/userlist.html")
	public String getUserList(Model model,
							@RequestParam(value="queryname",required=false) String queryUserName,
							@RequestParam(value="queryUserRole",required=false) String queryUserRole,
							@RequestParam(value="pageIndex",required=false) String pageIndex){
		logger.info("getUserList ---- > queryUserName: {}" , queryUserName);
		logger.info("getUserList ---- > queryUserRole: {}" , queryUserRole);
		logger.info("getUserList ---- > pageIndex: {}" , pageIndex);
		int _queryUserRole = 0;		
		List<User> userList = null;
		//设置页面容量
    	int pageSize = Constants.pageSize;
    	//当前页码
    	int currentPageNo = 1;
	
		if(queryUserName == null){
			queryUserName = "";
		}
		if(queryUserRole != null && !queryUserRole.equals("")){
			_queryUserRole = Integer.parseInt(queryUserRole);
		}
		
    	if(pageIndex != null){
    		try{
    			currentPageNo = Integer.valueOf(pageIndex);
    		}catch(NumberFormatException e){
    			return "redirect:/user/syserror.html";
    			//response.sendRedirect("syserror.jsp");
    		}
    	}	
    	//总数量（表）	
    	int totalCount	= userService.getUserCount(queryUserName,_queryUserRole);
    	//总页数
    	PageSupport pages=new PageSupport();
    	pages.setCurrentPageNo(currentPageNo);
    	pages.setPageSize(pageSize);
    	pages.setTotalCount(totalCount);
    	int totalPageCount = pages.getTotalPageCount();
    	//控制首页和尾页
    	if(currentPageNo < 1){
    		currentPageNo = 1;
    	}else if(currentPageNo > totalPageCount){
    		currentPageNo = totalPageCount;
    	}
		userList = userService.getUserList(queryUserName,_queryUserRole,currentPageNo,pageSize);
		model.addAttribute("userList", userList);
		List<Role> roleList = null;
		roleList = roleService.getRoleList();
		model.addAttribute("roleList", roleList);
		model.addAttribute("queryUserName", queryUserName);
		model.addAttribute("queryUserRole", queryUserRole);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("currentPageNo", currentPageNo);
		return "userlist";
	}
	
	@RequestMapping(value="/toadd.html")
	public String toAdd(@ModelAttribute("user") User user){
		return "useradd";
	}
	@PostMapping(value="/add.html")
	public String add(User user){
		System.out.println(user);
		boolean flag = userService.add(user);
		if (!flag) {
			
			return "redirect:toadd.html";
		}
		return "forward:userlist.html";
	}
	
	@GetMapping("/view/{id}")
	public String view(@PathVariable String id,Model model) {
		model.addAttribute("user", userService.getUserById(id));
		return "userview";
	}
	
	// 1 timestamp --> Date  2、对象 --> JSON对象
	@ResponseBody
//	@GetMapping(value = "/views/{id}",produces = {"application/json;charset=UTF-8"})
	@GetMapping(value = "/views/{id}")
	public Object view(@PathVariable String id) {
		User user = userService.getUserById(id);
		System.err.println(user);
		
		//JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd";;
		//return JSON.toJSONString(user, SerializerFeature.WriteDateUseDateFormat);
		return user;
	}
	
	
	@GetMapping(value="/add")
	public String add2(@ModelAttribute("user") User user){
		return "user/useradd";
	}
	@PostMapping(value="/add")
	public String add2(@Valid User user, BindingResult bindingResult, HttpSession session){
		
		System.out.println(user);
		if (bindingResult.hasErrors()) {
			return "user/useradd";
		}
		
		System.out.println(user);
		boolean flag = userService.add(user);
		if (!flag) {
			
			return "redirect:add";
		}
		return "forward:userlist.html";
	}
	
	@PostMapping(value="/add3.html")
	public String add3(User user,@RequestParam(value = "a_idPicPath") MultipartFile attch) throws IllegalStateException, IOException{
		
		String realFileName = attch.getOriginalFilename();
		System.out.println(realFileName);
		
		attch.transferTo(new File("D:\\upload",System.currentTimeMillis()+ realFileName));
		
		System.out.println(user);
		boolean flag = true;// userService.add(user);
		if (!flag) {
			
			return "redirect:toadd.html";
		}
		return "forward:userlist.html";
	}
	@PostMapping(value="/add4.html")
	public String add4(User user,@RequestParam(value = "attachs") MultipartFile[] attch) throws IllegalStateException, IOException{
		
		for (int i = 0; i < attch.length; i++) {
			System.out.println(attch[i].getSize());
			if (attch[i].getSize()> 0) {
				String realFileName = attch[i].getOriginalFilename();
				System.out.println(realFileName);
				
				attch[i].transferTo(new File("D:\\upload",System.currentTimeMillis()+ realFileName));		
			}
			
		}
		
		
		System.out.println(user);
		boolean flag = true;// userService.add(user);
		if (!flag) {
			
			return "redirect:toadd.html";
		}
		return "forward:userlist.html";
	}
	
	@ResponseBody
	@GetMapping("/ucexist.html")
	public String ucexist(String userCode) {
		User user = userService.selectUserCodeExist(userCode);
		JSONObject result = new JSONObject();
		if (user != null) {
			result.put("userCode", "exist");
		} else {
			result.put("userCode", "notexist");
		}
		System.out.println(result.toString());
		return result.toString();
	}
}
